package com.candy.biz.manager;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.candy.biz.domain.entity.SysRole;
import com.candy.biz.domain.param.SysRoleSaveParam;
import com.candy.biz.domain.vo.SysRoleVO;
import com.candy.biz.mapper.SysRoleMapper;
import com.candy.common.domain.PageVO;
import com.candy.common.enums.AdminErrorEnum;
import com.candy.common.utils.Assert;
import com.mybatisflex.core.paginate.Page;
import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import static com.candy.biz.domain.entity.table.SysRoleTableDef.SYS_ROLE;

/**
 * 系统角色-通用处理层。
 *
 * @author rong xi
 * @date 2023/09/18 09:18
 * @version 1.0.0
 */
@Component
@AllArgsConstructor
@Slf4j
public class SysRoleManager {

    private static SysRoleManager manager;
    private final SysRoleMapper sysRoleMapper;

    @PostConstruct
    private void init(){
        manager = this;
    }


    /**
     * 系统角色po对象转系统角色vo对象
     * @param po po对象
     * @return vo对象
     */
    public static SysRoleVO poToVo(SysRole po){
        return CommonManager.convert(po, SysRoleVO.class);
    }

    /**
     * 系统角色分页对象转换分页视图数据
     * @param page 分页结果
     * @return 分页数据
     */
    public static PageVO<SysRoleVO> pageToPageVO(Page<SysRole> page) {
        //转换处理
        return PageVO.of(posToVos(page.getRecords()),page.getTotalRow());
    }

    /**
     * 系统角色po集合转系统角色vo集合
     * @param pos po集合对象
     * @return vos vo集合对象
     */
    public static List<SysRoleVO> posToVos(List<SysRole> pos){
        return CommonManager.convert(pos, SysRoleVO.class);
    }

    /**
     * 新增系统角色准备
     * @param param 新增参数
     * @return po对象
     */
    public static SysRole insertPrepare(SysRoleSaveParam param){
        SysRole sysRole = BeanUtil.copyProperties(param, SysRole.class);
        //判断用户是否存在
        long count = manager.sysRoleMapper.selectCountByCondition(SYS_ROLE.ROLE_CODE.eq(param.getRoleCode()));
        Assert.isTrue(count == 0, AdminErrorEnum.ROLE_ALREADY_EXISTS);

        sysRole.setId(IdUtil.getSnowflakeNextId());
        sysRole.setCreateUser(StpUtil.getLoginIdAsLong());
        sysRole.setCreateTime(LocalDateTime.now());
        return sysRole;
    }

    /**
     * 修改系统角色准备
     * @param param 修改参数
     * @return po对象
     */
    public static SysRole updatePrepare(SysRoleSaveParam param){
        SysRole sysRole = BeanUtil.copyProperties(param, SysRole.class);
        sysRole.setUpdateUser(StpUtil.getLoginIdAsLong());
        sysRole.setUpdateTime(LocalDateTime.now());
        return sysRole;
    }

}
